<template>
  <div class="app-container">
    <!-- 筛选 -->
    <el-card>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>

        <el-form-item label="库位号">
          <el-input
            v-model="queryParams.storageNo"
            placeholder="请输入库位号"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item label="料号">
          <el-input
            v-model="queryParams.materialNo"
            placeholder="请输入料号"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item label="报关单号">
          <el-input
            v-model="queryParams.customsNo"
            placeholder="请输入报关单号"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item label="许可证号">
          <el-input
            v-model="queryParams.licenseNo"
            placeholder="请输入许可证号"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item label="品名">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入品名"
            clearable
            @keydown.enter.native.prevent="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt20">
      <el-row
        justify="space-between"
        class="mb10"
        v-hasPermi="['production:infeed:remove']"
      >
        <span style="font-size: 18px">出库记录</span>
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新增出库</el-button
        >
      </el-row>

      <el-table :data="inFeedList" border stripe v-loading="loading">
        <el-table-column prop="outboundTime" label="日期" />
        <el-table-column prop="materialNo" label="料号" />
        <el-table-column prop="productName" label="品名" />
        <el-table-column prop="storageNo" label="库位号" />
        <el-table-column prop="customsNo" label="报关单号" />
        <el-table-column prop="transferNo" label="调运单号" />
        <el-table-column prop="licenseNo" label="许可证号" />
        <el-table-column prop="orderNo" label="工单号" />
        <el-table-column prop="outboundNumber" label="出库数量(吨)" />
        <el-table-column prop="recordTime" label="记账日期" width="170">
          <template v-slot:default="{ row }">
            <div>
              {{
                row.recordTime
                  ? dayjs(row.recordTime).format("YYYY-MM-DD HH:mm:ss")
                  : ""
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="licenseTime" label="凭证日期" width="170">
          <template v-slot:default="{ row }">
            <div>
              {{
                row.licenseTime
                  ? dayjs(row.licenseTime).format("YYYY-MM-DD HH:mm:ss")
                  : ""
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewDetail(row)"
              >编辑</el-button
            >
            <el-button link type="danger" @click="deleteRow(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? '编辑出库记录' : '新增出库记录'"
      width="600px"
    >
      <el-form :model="formData" label-width="130px">
        <el-form-item label="日期">
          <el-date-picker
            v-model="formData.outboundTime"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="料号">
          <el-input v-model="formData.materialNo" />
        </el-form-item>

        <el-form-item label="品名">
          <el-input v-model="formData.productName" />
        </el-form-item>

        <el-form-item label="库位号">
          <el-input v-model="formData.storageNo" />
        </el-form-item>

        <el-form-item label="报关单号">
          <el-input v-model="formData.customsNo" />
        </el-form-item>

        <el-form-item label="调运单号">
          <el-input v-model="formData.transferNo" />
        </el-form-item>

        <el-form-item label="许可证号">
          <el-input v-model="formData.licenseNo" />
        </el-form-item>

        <el-form-item label="工单号">
          <el-input v-model="formData.orderNo" />
        </el-form-item>

        <el-form-item label="出库数量(吨)">
          <el-input-number
            v-model="formData.outboundNumber"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="记账日期">
          <el-date-picker
            v-model="formData.recordTime"
            type="date"
            placeholder="选择记账时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="凭证日期">
          <el-date-picker
            v-model="formData.licenseTime"
            type="date"
            placeholder="选择凭证时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  outboundList,
  outboundAdd,
  outboundEdit,
  outboundDelete,
} from "@/api/wms/outbound";
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import {
  queryLicenseList,
  queryCustomsNoList,
  getWorkList,
} from "@/api/wms/whole";

const loading = ref(false);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  storageNo: "",
  materialNo: "",
  customsNo: "",
  licenseNo: "",
  productName: "",
  outboundStartTime: "",
  outboundEndTime: "",
});

const inFeedList = ref([]);

// 下拉选项
const licenseOptions = ref([]);
const customsOptions = ref([]);
const workOptions = ref([]);
// 日期范围
const dateRange = ref([]); // [start, end]

async function handleQuery() {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.outboundStartTime = dateRange.value[0];
    queryParams.outboundEndTime = dateRange.value[1];
  } else {
    queryParams.outboundStartTime = "";
    queryParams.outboundEndTime = "";
  }
  loading.value = true;
  try {
    const res = await outboundList(queryParams);
    res.rows.forEach((element) => {
      element.incomeTon = (element.incomeTon / 1000).toFixed(4);
      element.scrapKg = (element.scrapKg / 1000).toFixed(0);
    });
    inFeedList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (err) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
}

function viewDetail(row) {
  Object.assign(formData, {
    ...row,
  });
  dialogVisible.value = true;
}

function resetQuery() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    storageNo: "",
    materialNo: "",
    customsNo: "",
    licenseNo: "",
    productName: "",
    outboundStartTime: "",
    outboundEndTime: "",
  });
  dateRange.value = [];
  handleQuery();
}

const dialogVisible = ref(false);

const formData = reactive({
  id: null,
  outboundTime: "", // 日期
  materialNo: "", // 料号
  productName: "", // 品名
  storageNo: "", // 库位号
  customsNo: "", // 报关单号
  transferNo: "", // 调运单号
  licenseNo: "", // 许可证号
  orderNo: "", // 工单号
  outboundNumber: null, // 出库数量(吨)
  recordTime: "", // 记账日期
  licenseTime: "", // 凭证日期
});

function calcWasteWeight() {}

function handleAdd() {
  Object.assign(formData, {
    id: null,
    outboundTime: "", // 日期
    materialNo: "", // 料号
    productName: "", // 品名
    storageNo: "", // 库位号
    customsNo: "", // 报关单号
    transferNo: "", // 调运单号
    licenseNo: "", // 许可证号
    orderNo: "", // 工单号
    outboundNumber: null, // 出库数量(吨)
    recordTime: "", // 记账日期
    licenseTime: "", // 凭证日期
  });
  dialogVisible.value = true;
}

async function submitForm() {
  calcWasteWeight();
  formData.outboundTime = dayjs(formData.outboundTime).format("YYYY-MM-DD");
  formData.recordTime = dayjs(formData.outboundTime).format("YYYY-MM-DD");
  formData.licenseTime = dayjs(formData.outboundTime).format("YYYY-MM-DD");
  try {
    if (formData.id) {
      await outboundEdit(formData);
      ElMessage.success("更新成功");
    } else {
      await outboundAdd(formData);
      ElMessage.success("新增成功");
    }
    dialogVisible.value = false;
    handleQuery();
  } catch (err) {
    ElMessage.error("提交失败");
  }
}

async function loadSelectOptions() {
  try {
    const [workRes] = await Promise.all([getWorkList()]);
    workOptions.value = workRes.data.filter((pre) => pre) || [];
  } catch (e) {
    ElMessage.error("加载下拉选项失败");
  }
}

function deleteRow(row) {
  ElMessageBox.confirm("是否删除此项?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await outboundDelete(row.id);
      ElMessage.success("删除成功");
      handleQuery();
    } catch (err) {
      ElMessage.error("删除失败");
    }
  });
}

// 初始化
onMounted(() => {
  handleQuery();
  loadSelectOptions();
});
</script>

<style scoped>
.mt20 {
  margin-top: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.pagination-wrapper {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
